#!/usr/bin/env ruby -wKU
#encoding: UTF-8

require 'backend/model/TNovel'
require 'backend/model/TVolume'
require 'backend/model/TChapter'

module TiebaData

  # FIX issue that \w* cannot match chinese characters
  # NamingPtn = /(\d+)_(\w*)/
  NamingPtn = /(\d+)_(.*)/
  
  class TChapterLoader
    
    def loadNovels(novels)
      if (novels.nil?)
        $logger.info(__FILE__) { __LINE__.to_s + " => argument is nil" }
        return
      end

      novels.each do |novel|
        volumes, maxVolNo = loadVolumes(novel)
        return if volumes.nil?

        $logger.info(__FILE__) { __LINE__.to_s + " => max volume no is " + maxVolNo.to_s }

        volumes.each do |volume|

          chapters, maxChpNo = loadChapters(volume)
          return if chapters.nil?

          $logger.info(__FILE__) { __LINE__.to_s + " => max chapter no is " + maxChpNo.to_s }

          chapters.each do |chapter|
            volume.addChapter(chapter)
          end
          volume.maxChpNo = maxChpNo

          novel.addVolume(volume)
        end
        novel.maxVolNo = maxVolNo
      end

    end

    # load all volumes belong to @param novel but with no chapter related info set
    def loadVolumes(novel)
      return nil, nil if novel.nil?

      novelDir = novel.storageDir
      return nil, nil unless Dir.exist? novelDir

      volumes = []
      max = 0
      Dir.foreach(novelDir) do |f|
        if File.directory? novelDir + "/" + f
          if (match = f.match(NamingPtn))
            no, name = match.captures
            # create a new volume instance
            volume = Model::TVolume.new(novel)
            volume.volNo = no.to_i unless no.nil?
            volume.volName = name unless name.nil?
            
            volumes << volume
            
            max = volume.volNo if volume.volNo > max
          end
        end

      end

      return volumes, max
    end

    # load all chapters belong to @param volume but with no content loaded
    def loadChapters(volume)
      reutrn nil, nil if volume.nil?

      chpDir = volume.storageDir
      return nil, nil unless Dir.exist? chpDir

      chapters = []
      max = 0
      Dir.foreach chpDir do |f|
        if File.file? chpDir + "/" + f
          if (match = f.match(NamingPtn))
            no, name = match.captures
            # create a new chapter instance
            chapter = Model::TChapter.new(volume)
            chapter.chpNo = no.to_i unless no.nil?
            chapter.chpName = name unless name.nil?
            
            chapters << chapter
            
            max = chapter.chpNo if chapter.chpNo > max
          end
        end
      end

      return chapters, max
    end
    
    # load chapter content
    def loadChapterContent(chapter)
      return if chapter.nil?

      chpPath = chapter.storagePath
      return unless File.exist? chpPath

      File.open(chpPath, 'r') do |f|
        f.flock(File::LOCK_SH)
        chpater.content = f.read
      end
    end

  end

end
